
var log = function(msg){
	var logWin = $('#logger');
	if(logWin.length == 0){
		var logger = $('<div id="logger" />');
			logger.css("width", 320);
			logger.css("height", 800);
			logger.css("display", "block");
			logger.css("right", 0);
			logger.css("top", 0);
			logger.css("position", "absolute");
		    logger.css("border", "solid 1px red");
	    $('body').append(logger);
	}
	
	if(window.console){
		window.console.log(msg);
	}else{
		$('#logger').append($('<span>'+ msg +'</span><br/>'));
	}
	// NOTE: log to the screen anyway
	$('#logger').append($('<span>'+ msg +'</span><br/>'));
}



var inspectContent = function(){
	
	
};

var addEntity = function(elemObj, parentObj){
	var nodeName = elemObj.context.nodeName;
	var thisElem = elemObj;
	switch(nodeName.toLowerCase()){
		case 'button':
			var label = thisElem.attr("label");
	    	var elem = $('<a>'+ label +'</a>');
	    		elem.css("border", "solid 1px red");
	    		elem.css("padding", "4px");
	    		elem.click(function(){
	    			var method = thisElem.attr("onClick");
	    			//alert(method);
	    			eval(method);
	    		});
			$(parentObj).append(elem);
    		thisElem.remove();
		
		break;
		case 'canvas':
			var width  = thisElem.attr("width");
			var height = thisElem.attr("height");
			var id = thisElem.attr("id");
	    	var elem = $('<div id="'+ id +'"/>');
	    		elem.css("border", "solid 1px red");
	    		elem.css("padding", "4px");
				elem.css("width", width);
				elem.css("height", height);
			$(parentObj).append(elem);
				//alert("thisElem.children().length: " + thisElem.children().length);
			if(thisElem.children().length > 0){
				var childrenElem = thisElem.children();
					childrenElem.each(function(){
						var parentObj = 
						addEntity($(this), elem);
					});
			}else{
    			//thisElem.remove();
			}
		break;
		default:
	}
	
	if(thisElem){
		//thisElem.remove();
	}
	
};
 
jQuery(function($){
    log("page loaded");
	var view = $('<div/>');
	var data = $('<div/>');
    $('script[type="text/jsmxml"]').each(function(){
    	
    	view.attr("id",  $(this).attr("id"));
		view.insertBefore($(this));
    	var content = $(this).html();
		// replace 'click' string
			content = content.split("click").join("onClick");
    	data.append($("'"+content+"'"));
    	
    	
    	var childrenElem = data.children();
    	$(childrenElem).each(function(){
			addEntity($(this), view);
		});
    	
    	
    	/*
		data.children().each(function(){
			var nodeName = $(this).context.nodeName;
			addEntity(nodeName, $(this));
		});*/
		$(this).remove();
    });
	
    
});